package com.lw.leetcode.arr.b;

import java.util.*;

/**
 * arr
 * 1418. 点菜展示表
 *
 * @Author liw
 * @Date 2021/7/6 9:24
 * @Version 1.0
 */
public class DisplayTable {
    public List<List<String>> displayTable(List<List<String>> orders) {
        Map<String, Map<String, Integer>> map = new HashMap<>();
        PriorityQueue<String> foodQue = new PriorityQueue<>();
        PriorityQueue<String> numQue = new PriorityQueue<>((o1, o2) -> Integer.parseInt(o1) - Integer.parseInt(o2));
        Set<String> foodSet = new HashSet<>();
        for (List<String> order : orders) {
            String num = order.get(1);
            String foodName = order.get(2);
            Map<String, Integer> cMap = map.get(num);
            if (cMap == null) {
                cMap = new HashMap<>();
                cMap.put(foodName, 1);
                map.put(num, cMap);
                numQue.add(num);
            } else {
                cMap.put(foodName, cMap.getOrDefault(foodName, 0) + 1);
            }
            if (!foodSet.contains(foodName)) {
                foodQue.add(foodName);
                foodSet.add(foodName);
            }
        }
        List<List<String>> ret = new ArrayList<>();
        List<String> row = new ArrayList<String>() {{
            add("Table");
            while (!foodQue.isEmpty()) {
                add(foodQue.poll());
            }
        }};
        ret.add(new ArrayList<>(row));
        List<String> head = ret.get(0);
        int size = head.size();
        while (!numQue.isEmpty()) {
            row = new ArrayList<>();
            String num = numQue.poll();
            row.add(num);
            for (int i = 1; i < size; i++) {
                int cnt = map.get(num).getOrDefault(head.get(i), 0);
                row.add(String.valueOf(cnt));
            }
            ret.add(new ArrayList<>(row));
        }
        return ret;
    }
}
